var Client = require('ftp');
var fs = require('fs');

var Ftp = module.exports = function (options) {
    this.client = new Client();
    this.client.connect(options);

    this.client.on('error', function (err) {
        console.log(err);
    });
}

// +-----------------------------------------------------------------------
// |                       从服务器上下载一个文件
// +-----------------------------------------------------------------------
Ftp.prototype.download = function (localFilePath, remoteFilePath, cb) {
    var self = this;
    self.client.on( "ready", function() {
        console.log( "connected OK" );
        self.client.get( remoteFilePath, function( err, stream ) {
			if( err ) cb( err );
			if ( typeof stream == "undefined" ) return;
			stream.once( 'close', function() { self.client.end(); } );
			var writeStream = fs.createWriteStream( localFilePath );
			stream.pipe( writeStream );
			writeStream.on('finish', function() {
				writeStream.close();
                console.log( "下载完成" );
    			cb( null, true );
			});
		});
    });
}

// +-----------------------------------------------------------------------
// |                        上传一个文件到服务器
// +-----------------------------------------------------------------------
Ftp.prototype.upload = function (localFilePath, remoteFilePath, cb) {
    var self = this;
    var splitArr = remoteFilePath.split("/");
    var remoteDirectory = remoteFilePath.split(splitArr[splitArr.length - 1])[0];
    self.client.on('ready', function () {
        console.log( "连接成功" );
        
        self.client.mkdir(remoteDirectory, true, function (err) {
            if (err) console.log(err);
            else {
                console.log("创建目录");
                self.client.put(localFilePath, remoteFilePath, function (err) {
                    if (err) console.log(err);
                    console.log("上传文件");
                    self.client.end();
                });
            }
        });
    });
}